package com.example.springbootshirp.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @author 墨苍璃
 */
@Controller
public class MyController {

    /**
     * 声明单元方法:跳转登录页面
     *
     * @return
     */
    @RequestMapping("login")
    public String loginPage() {
        return "login";
    }


    /**
     * 声明单元方法:跳转主页面
     *
     * @return
     */
    @RequestMapping("main")
    public String getMainPage() {
        return "main";
    }


    /**
     * 声明单元方法：用户登录
     *
     * @param uname
     * @param pwd
     * @param remember
     * @return
     */
    @RequestMapping("userLogin")
    public String userLogin(String uname, String pwd, @RequestParam(defaultValue = "false") Boolean remember) {
        //获取Subject对象
        Subject subject = SecurityUtils.getSubject();

        //创建对象存储认证信息
        AuthenticationToken token = new UsernamePasswordToken(uname, pwd, remember);

        System.out.println(token.getPrincipal().toString());
        System.out.println(":::::::::::::::::::::::");
        //调用Shiro的login方法完成登录认证
        try {
            //login()方法没有返回值，只能通过是否有异常判断是否登录成功。
            subject.login(token);
            return "redirect:/main";
        } catch (UnknownAccountException e) {
            System.out.println("账号不存在");
            return "redirect:/error";
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
            return "redirect:/error";
        } catch (ExcessiveAttemptsException e) {
            System.out.println("连续密码输入错误,账号锁定10分钟");
            return "redirect:/error";
        } catch (Exception e) {
            System.out.println("未知错误");
            e.printStackTrace();
            return "redirect:/error";
        }
    }


    /**
     * 声明单元方法:获取session中的数据
     *
     * @param session
     * @return
     */
    @RequestMapping("demoSession")
    @ResponseBody
    public String demoSession(HttpSession session) {
        //遍历session中的数据
        Enumeration<String> names = session.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object value = session.getAttribute(name);
            //打印结果
            System.out.println(name + "----" + value);
        }
        return "session取值";
    }

}
